﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：DatabaseConnectionWrapper.cs
// 功能描述：TongTongMall.Dapper
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TongTongMall.Dapper
{
    public class DatabaseConnectionWrapper : IDisposable
    {
        /// <summary>
        /// 原子锁标记
        /// </summary>
        private int refCount;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        public DatabaseConnectionWrapper(DbConnection connection)
        {
            Connection = connection;
            refCount = 1;
        }

        /// <summary>
        /// 数据连接对象
        /// </summary>
        public DbConnection Connection { get; private set; }

        public bool IsTransactionConnection { get; set; } = false;

        /// <summary>
        /// 释放后 加锁标记归0
        /// </summary>
        public bool IsDisposed
        {
            get { return refCount == 0; }
        }

        #region IDisposable Members

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "As designed. This is a reference counting disposable.")]
        public void Dispose()
        {
            Dispose(true);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "As designed. This is a reference counting disposable.")]
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                int count = Interlocked.Decrement(ref refCount);
                if (count == 0)
                {
                    if (Connection.State == System.Data.ConnectionState.Open)
                        Connection.Close();
                    Connection.Dispose();
                    Connection = null;
                    GC.SuppressFinalize(this);
                }
            }
        }

        #endregion


        public DatabaseConnectionWrapper AddRef()
        {
            Interlocked.Increment(ref refCount);
            return this;
        }
    }
}
